import { Button, Checkbox, Col, Form, Image, Input, Row } from 'antd';
import CryptoJS from 'crypto-js';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import logo from '@/assets/images/hywl.png';
import Captcha, { CaptchaActionType } from '@/pages/sys/login/CaptchaForm';
import { useSignIn } from '@/store/userStore';

import { LoginStateEnum, useLoginStateContext } from './providers/LoginStateProvider';

const SECRET_KEY = '2pFYwcQVGPu2HMx4AQt33RdMu2UjS6DY';

function LoginForm() {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);

  const { loginState, setLoginState } = useLoginStateContext();
  const signIn = useSignIn();
  const [form] = Form.useForm();
  // 【新增】：创建 Ref 来控制 Captcha 组件
  const captchaRef = useRef<CaptchaActionType | null>(null);

  useEffect(() => {
    const storedData = localStorage.getItem('rememberUser');
    if (storedData) {
      try {
        const { code, password } = JSON.parse(storedData);
        const bytes = CryptoJS.AES.decrypt(password, SECRET_KEY);
        const decrypted = bytes.toString(CryptoJS.enc.Utf8);
        form.setFieldsValue({ code, password: decrypted, remember: true });
      } catch (e) {
        console.error('Failed to parse stored credentials', e);
      }
    }
  }, [form]);

  if (loginState !== LoginStateEnum.LOGIN) return null;

  const onFinish = async (values) => {
    setLoading(true);
    const captchaProps = form.getFieldValue('captchaProps');
    try {
      await signIn({
        code: values.code as string,
        password: values.password as string,
        app: values.app as string,
        remember: values.remember as boolean,
        captcha: captchaProps.captcha,
        uuid: captchaProps.uuid,
      });
    } catch (error: any) {
      // 【关键逻辑】：捕获错误并处理验证码重置
      // 根据你的后端响应，error.message 是 "验证码输入错误"
      // 也可以根据 error.code === 'ERROR.CACHE.CHALLENGER.SECRET_NOT_MATCH' 来判断，这更稳健

      const isCaptchaError =
        error?.message?.includes('验证码') ||
        error?.code === 'ERROR.CACHE.CHALLENGER.SECRET_NOT_MATCH';

      if (isCaptchaError) {
        // 1. 调用子组件的 reset 方法（清空输入框 inputCode + 刷新图片）
        captchaRef.current?.reset();
        // 2. 清空 Antd Form 中的字段值，防止下一次提交时带上旧的 uuid 或 code
        form.setFields([
          {
            name: 'captchaProps',
            value: { captcha: '', uuid: '' }, // 设置表单值为“空”
            errors: [error.message || '验证码输入错误'], // <--- 强行显示红色的错误提示
          },
        ]);
      }
      // 注意：message.warning 已经在 useSignIn 里弹出了，这里不需要重复弹
    } finally {
      if (values.remember) {
        // aes加密
        const encrypted = CryptoJS.AES.encrypt(values.password, SECRET_KEY).toString();
        localStorage.setItem(
          'rememberUser',
          JSON.stringify({
            code: values.code,
            password: encrypted,
          }),
        );
      } else {
        localStorage.removeItem('rememberUser');
      }
      setLoading(false);
    }
  };
  return (
    <div>
      <div style={{ width: '100%', textAlign: 'center', position: 'relative', bottom: '17%' }}>
        <Image src={logo} preview={false} style={{ width: '45%', display: 'inline-block' }} />
      </div>
      <div className="mb-4 text-2xl font-bold xl:text-3xl">{t('sys.login.signInFormTitle')}</div>
      <Form
        name="login"
        size="large"
        form={form}
        initialValues={{
          remember: true,
          code: '',
          password: '',
        }}
        onFinish={onFinish}
      >
        <Form.Item
          name="code"
          rules={[{ required: true, message: t('sys.login.accountPlaceholder') }]}
        >
          <Input autoComplete="code" placeholder={t('sys.login.userName')} />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: t('sys.login.passwordPlaceholder') }]}
        >
          <Input.Password
            autoComplete="password"
            type="password"
            placeholder={t('sys.login.password')}
          />
        </Form.Item>
        <Form.Item name="captchaProps" rules={[{ required: true, message: '请输入验证码' }]}>
          <Captcha
            actionRef={captchaRef}
            onCaptchaChange={(captcha, uuid) => {
              form.setFieldValue('captchaProps', { captcha, uuid });
            }}
            placeholder="请输入验证码"
          />
        </Form.Item>
        <Form.Item>
          <Row align="middle">
            <Col span={12}>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>{t('sys.login.rememberMe')}</Checkbox>
              </Form.Item>
            </Col>
            {/* <Col span={12} className="text-right"> */}
            {/*  <Button */}
            {/*    type="link" */}
            {/*    className="!underline" */}
            {/*    onClick={() => setLoginState(LoginStateEnum.RESET_PASSWORD)} */}
            {/*    size="small" */}
            {/*  > */}
            {/*    {t('sys.login.forgetPassword')} */}
            {/*  </Button> */}
            {/* </Col> */}
          </Row>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="w-full" loading={loading}>
            {t('sys.login.loginButton')}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default LoginForm;
